package com.zhoug.player.vlcplayer;

import android.content.Context;

import com.zhoug.player.core.utils.LogUtils;

import org.videolan.libvlc.LibVLC;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @author: zhoug
 * @since: 2025-08-13
 */
public class VLCManager {
    private static final String TAG = ">>>VLCManager";
    private static volatile LibVLC instance;
    private static ArrayList<String> options;
    private static final Object sLock = new Object();
    private static volatile boolean isReleased = false;
    private static volatile boolean isInitializing = false;

    private static final List<Callback> pendingCallbacks = new ArrayList<>();

    public static void setOptions(ArrayList<String> options) {
        VLCManager.options = options;
    }


    @Nullable
    public static LibVLCWrapper getInstance() {
        if (isReleased || instance==null) return null;
        return new LibVLCWrapper(instance);
    }


    public static void init(Context context, @NonNull Callback callback) {
        // 快速检查（避免同步块开销）
        if (instance != null) {
            callback.onSuccess();
            return;
        }
        synchronized (sLock) {
            // 二次检查（避免竞态）
            if (instance != null) {
                callback.onSuccess();
                return;
            }
            // 释放则拒绝新请求
            if (isReleased) {
                callback.onFailure("LibVLC is being released");
                return;
            }
            // 加入回调队列
            pendingCallbacks.add(callback);
            // 若已开始初始化则直接返回（等待回调）
            if (isInitializing) {
                return;
            }
            // 标记初始化开始
            isInitializing = true;
            new Thread(() -> {
                // 初始化
                LibVLC libVLC = null;
                String error = null;
                try {
                    libVLC = new LibVLC(context, options != null ? options : new OptionsBuilder().build());
                } catch (Exception e) {
                    error = e.getMessage();
                    LogUtils.e(TAG, "LibVLC初始化失败:" + error);
                }
                // 同步更新状态
                synchronized (sLock) {
                    if (libVLC != null) {
                        instance = libVLC;
                    }
                    isInitializing = false;
                    // 处理所有等待的回调
                    for (Callback cb : pendingCallbacks) {
                        if (libVLC != null) {
                            cb.onSuccess();
                        } else {
                            cb.onFailure(error);
                        }
                    }
                    pendingCallbacks.clear();
                }
            }).start();
        }
    }

    /**
     * 释放LibVLC资源
     */
    public static void release() {
        synchronized (sLock) {
            if (instance == null || isReleased) return;
            isReleased = true;
            final LibVLC toRelease = instance;
            instance = null;
            new Thread(() -> {
                try {
                    toRelease.release();
                } catch (Exception e) {
                    LogUtils.e(TAG, "release:" + e.getMessage());
                }
            }).start();
        }

    }


    public interface Callback {
        void onSuccess();

        void onFailure(String error);
    }

    public static class LibVLCWrapper {

        private final LibVLC libVLC;

        private LibVLCWrapper(@NonNull LibVLC libVLC) {
            this.libVLC = libVLC;
        }

        @NonNull
        public LibVLC get() {
            return libVLC;
        }
    }

}
